package nl.ypmits.utils.as3.bitmap {
	import nl.ypmits.utils.as3.math.SimpleMath;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.GradientType;
	import flash.display.Shape;
	import flash.display.SpreadMethod;
	import flash.display.Sprite;
	import flash.geom.Matrix;

	/**
	 * @author davelenz
	 * @version 1 (eerste opzet)
	 * @version 1.1 (moving toegevoegd)
	 */
	public class MirrorTool {

		/**
		 * BitmapTool.mirror is used to mirror a DisplayObject
		 * </br>
		 * @author davelenz
		 * @version 1
		 * </br>
		 * Usage: <code>BitmapTool.mirror</code> returns a clone of the bitmap you put in.
		 * </br>
		 * @param bitmap The bitmap to mirror
		 * @param startalpha The alpha-value on top from 0 to 1. Default is 1
		 * @param endalpha The alpha-value below from 0 to 1. Default = 0
		 * @param percentageofbitmap The percentage-height of the bitmap to use for the fade
		 * @param yOffset The offset of the mirrored bitmap
		 */
		public static function mirror( obj : DisplayObject, startalpha : Number = 1, endalpha : Number = 0, percofbitmap : Number = 1, yOffset : Number = 0 ) : Sprite {
			var holder : Sprite = new Sprite( );

			var m : Matrix = new Matrix( );
			m.translate( 0, -obj.height );
			m.scale( 1, -1 );
			var bitmapdata : BitmapData = new BitmapData( obj.width, obj.height, true, 0xFF9900 );

			var newbitmap : Bitmap = new Bitmap( bitmapdata );
			bitmapdata.draw( obj, m );
			newbitmap.y = yOffset;
			newbitmap.smoothing = true;
			holder.addChild( newbitmap );

			var gradientmasker : Shape = getMirrorGradient( newbitmap, startalpha, endalpha, percofbitmap );
			gradientmasker.y = yOffset;
			holder.addChild( gradientmasker );

			newbitmap.cacheAsBitmap = true;
			gradientmasker.cacheAsBitmap = true;
			newbitmap.mask = gradientmasker;

			return holder;
		}
		
		private static function getMirrorGradient( bitmap : Bitmap, startalpha : Number = 1, endalpha : Number = 0, percofbitmap : Number = 1 ) : Shape {
			var m : Matrix = new Matrix( );
			m.createGradientBox( bitmap.width, percofbitmap * bitmap.height, SimpleMath.degreesToRadians( 90 ) );

			var gradient : Shape = new Shape( );
			gradient.graphics.clear( );
			gradient.graphics.beginGradientFill( GradientType.LINEAR, [0xFF9900, 0xFF9900], [startalpha, endalpha], [0, 255], m, SpreadMethod.PAD );  
			gradient.graphics.drawRect( 0, 0, bitmap.width, percofbitmap * bitmap.height );
			gradient.graphics.endFill( );

			return gradient;
		}
	}
}
